package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.baiduFace.AipFaceTemplate;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.Log;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.vo.UserInfoVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserManager {
    @DubboReference
    private UserService userService;

    public Long save(User user) {
        user.setPassword("123456");
        Long saveId = userService.save(user);
        return saveId;
    }

    public User findByPhone(String phone) {
        User byPhone = userService.findByPhone(phone);
        return byPhone;
    }

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //发短信
    public void sendSmsLoginOrRegister(String phone) {
//        String code = RandomUtil.randomNumbers(6);
//        smsTemplate.sendSms(phone,code);

        //TODO 以后改成动态验证码发送,测试阶段先写死
        String code = "123456";
        stringRedisTemplate.opsForValue()
                .set(ConstantUtil.SMS_CODE + phone, code, 5, TimeUnit.MINUTES);
    }

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //注册或者登录
    public ResponseEntity loginOrRegister(String phone, String verificationCode) {
        String code = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        if (!StrUtil.equals(verificationCode, code)) {
            return ResponseEntity.status(500).body("验证码错误");
        }
        //查询数据库是否有此用户
        User byPhone = this.findByPhone(phone);
        boolean isNew = false;
        if (byPhone == null) {
//            执行注册
            byPhone = new User();
            byPhone.setMobile(phone);
            Long saveId = this.save(byPhone);
            byPhone.setId(saveId);
            isNew = true;
            //注册环信用户
            huanXinTemplate.register("HX" + saveId);

            //记录日志 - 注册日志

            //记录日志 -注册日志
            Log log = new Log();
            log.setUserId(saveId);//操作人
            log.setPlace("北京顺义"); //操作地点  读取mongo
            log.setEquipment("小米9");//操作设备
            log.setType("0102");//操作类型  注册
            log.setLogTime(DateUtil.formatDate(new Date()));//操作时间
            //发送消息
            rabbitTemplate.convertAndSend("tanhua.log", log);
        } else {
            //记录日志 - 登录日志
            //记录日志 -注册日志
            Log log = new Log();
            log.setUserId(byPhone.getId());//操作人
            log.setPlace("北京顺义"); //操作地点  读取mongo
            log.setEquipment("小米9");//操作设备
            log.setType("0101");//操作类型  注册
            log.setLogTime(DateUtil.formatDate(new Date()));//操作时间
            //发送消息
            rabbitTemplate.convertAndSend("tanhua.log", log);

        }
        //不管是注册还是登录 , 生成一个token返回给客户端用以保存登录状态
        Map tokenMap = new HashMap<>();
        tokenMap.put("id", byPhone);
        tokenMap.put("mobile", byPhone.getMobile());
        String token = JwtUtil.createToken(tokenMap);

        //转换为缓存可以保存的字符串(其实无所谓什么值)
        String json = JSON.toJSONString(byPhone);

        //服务器保存一个缓存 ,用以校验以后是否需要重新登录
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, 7, TimeUnit.DAYS);

        //登录(注册)成功 , 删除验证码
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + phone);

        Map returnMap = new HashMap();
        returnMap.put("token", token);
        returnMap.put("isNew", isNew);

        return ResponseEntity.ok(returnMap);
    }

    @DubboReference
    private UserInfoService userInfoService;

    public void saveUserInfo(UserInfo userInfo, String token) {
        //赋值默认值
        userInfo.setIncome("50");
        userInfo.setEducation("本科");
        userInfo.setProfession("无业");
        userInfo.setMarriage(0);
        userInfo.setTags("单身,本科,年龄相仿");
        userInfo.setAge(20);

        //User user = findUserByToken(token);
        User user = UserHolder.getLocal();
        userInfo.setId(user.getId());
        userInfoService.save(userInfo);

    }


//    private User findUserByToken(String token) {
//        if (token != null) {
//            String userJson = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);
//            User user = JSON.parseObject(userJson, User.class);
//            //续期token
//            stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, 7, TimeUnit.DAYS);
//
//            return user;
//        }
//        return null;
//    }


    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    /**
     * 更新用户头像
     * 1.人脸识别
     * 2.上传到oss的平台上
     * 3.解析id
     * 4.根据id和 上传的oss平台返回的图片的路径 修改到数据库
     */
    public void saveUserHead(MultipartFile headPhoto, String token) throws IOException {
        if (headPhoto != null && headPhoto.getSize() > 0) {//图片一定存在
            //1.人脸识别
//            System.out.println("进入图片saveUserHead");
//            System.out.println("图片大小" + headPhoto.getSize());
//            System.out.println("图片名字" + headPhoto.getOriginalFilename());

            boolean flag = aipFaceTemplate.detect(headPhoto.getBytes());
            if (!flag) {
                throw new RuntimeException("人脸识别不通过");
            }
            //2.上传到oss的平台上
            String picPath = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
            //3.解析id
//            User user = findUserByToken(token);
            User user = UserHolder.getLocal();
            //4.根据id和 上传的oss平台返回的图片的路径 修改到数据库
            UserInfo userInfo = new UserInfo();
            userInfo.setId(user.getId());//赋值id
            userInfo.setAvatar(picPath); //头像

            userInfoService.update(userInfo);
        }
    }

    public ResponseEntity findUserInfo(String userId, String token) {
        UserInfo userInfo = null;
        if (userId != null) {
            userInfo = userInfoService.findByUserId(Long.parseLong(userId));
            System.out.println(userInfo);
        } else {
//            User userByToken = findUserByToken(token);
            User userByToken = UserHolder.getLocal();
            System.out.println(userByToken);

//            System.out.println("userByToken.getId()---" + userByToken.getId());
            userInfo = userInfoService.findByUserId(userByToken.getId());
            System.out.println(userInfo);
        }

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo, userInfoVo);
        System.out.println(userInfoVo);


        return ResponseEntity.ok(userInfoVo);
    }

    public void updateUserInfo(UserInfo userInfo, String token) {
        //User userByToken = findUserByToken(token);
        User userByToken = UserHolder.getLocal();

        userInfo.setId(userByToken.getId());
        userInfoService.update(userInfo);
    }
}
